<?php
// 處室資料升級
class Default_Model_Upgrade_Schoolday extends Default_Model_Upgrade_Core
{
    protected $_table = 'school_day';
    protected $_targetTable = array('semester_duration','semester_week');

    function upgrade (){
        if ($this->isUpgrade())
        return 'isUpgrde';
        else {
            $query = "SELECT * FROM school_day";
            $res = $this->_sfs3Pdo->query($query)->fetchAll(PDO::FETCH_ASSOC);
            $log = array();
            $success_count = 0;
            $error_count = 0;
            $rank = 0;
            $arr = array();
            foreach($res as $row){
                switch($row['day_kind']) {
                    case 'start':
                        $temp= "started_date";
                        break;
                    case 'end':
                        $temp= "ended_date";
                        break;
                    case 'st_start':
                        $temp= "opened_date";
                        break;
                    case 'st_end':
                        $temp= "closed_date";
                        break;
                }

                $query = "SELECT year FROM semester_duration WHERE year={$row['year']} AND semester={$row['seme']}";
                $res2 = $this->_newdbPdo->query($query);//->fetchAll(PDO::FETCH_ASSOC);
                if ($res2->rowCount()>0) {
                    $query = "UPDATE semester_duration SET $temp='{$row['day']}' WHERE year={$row['year']}
					AND semester={$row['seme']}";
                    $this->_newdbPdo->exec($query);
                }
                else{
                    $arr = array();
                    $arr['year'] = $row['year'];
                    $arr['semester'] = $row['seme'];
                    $arr[$temp] = $row['day'];
                    $query  = "INSERT INTO  semester_duration (".implode(',',array_keys($arr)).") VALUES('".implode("','",array_values($arr))."')";
                    $this->_newdbPdo->exec($query);
                }

            }

            // 週次
            $query = "SELECT * FROM week_setup";
            $res = $this->_sfs3Pdo->query($query)->fetchAll(PDO::FETCH_ASSOC);
            foreach($res as $row) {
                $query  = "INSERT INTO  semester_week (".implode(',',array_keys($row)).") VALUES('".implode("','",array_values($row))."')";
                 $this->_newdbPdo->exec($query);
            }


        }



        $log['success_count'] = $success_count;
        $log['error_count'] = $error_count;
        $log['memo'] = '學期日期設定';
        $log['upgrade_time']	= date("Y-m-d h:i:s");

        $this->finishUpgrade($log);

    }

}